<?php

namespace app\admin\controller\group_activity\published;

use app\admin\service\ReportService;
use app\admin\service\UserService;
use app\BaseController;
use app\model\FollowUserModel;
use app\model\group_activity\GroupActivityTaskCommentModel;
use app\model\group_activity\GroupActivityTaskDepartmentModel;
use app\model\group_activity\GroupActivityTaskImgModel;
use app\model\group_activity\GroupActivityTaskModel;
use app\model\group_activity\GroupActivityTaskRatingScaleModel;
use app\model\group_activity\GroupActivityTaskUserModel;
use app\model\group_activity\GroupActivityTaskUserResultModel;
use app\model\UserModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 设置查看权限
     * @return bool|string
     */
    public function callableView(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|Id' => 'require',
                'callable_view|查看状态' => 'require'
            ]);
            $GroupActivityTaskUserResultModel = new GroupActivityTaskUserResultModel();
            $info = $GroupActivityTaskUserResultModel->find($param['id']);
            $info->save([
                'callable_view' => $param['callable_view']
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 加入关注
     * @return bool|string
     */
    public function addFollow(): bool|string
    {
        $GroupActivityTaskUserResultModel = new GroupActivityTaskUserResultModel();
        $GroupActivityTaskUserResultModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require|integer|max:11',
                'level|关注等级' => 'require',
                'reason|关注原因' => 'require',
            ]);
            $info = $GroupActivityTaskUserResultModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $FollowUserModel = new FollowUserModel();
            $FollowUserModel->insert([
                'unit_id' => $this->userData['unit_id'],
                'operator_uid' => $this->userData['id'],
                'uid' => $info['uid'],
                'level' => $param['level'],
                'reason' => $param['reason'],
                'channel' => 11,
                'channel_id' => $param['id'],
                'time' => time()
            ]);
            $info->save([
                'is_follow' => 1
            ]);
            $GroupActivityTaskUserResultModel->commit();
            return success();
        } catch (\Exception $e) {
            $GroupActivityTaskUserResultModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 查询任务状态
     * @return bool|string
     */
    public function taskStatus(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $GroupActivityTaskModel = new GroupActivityTaskModel();
            if (is_array($param['id'])) {
                $status = $GroupActivityTaskModel->where('id', 'in', $param['id'])->distinct(true)->column('status');
            } else {
                $status = $GroupActivityTaskModel->where('id', '=', $param['id'])->distinct(true)->column('status');
            }
            return success($status);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 已发布活动
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'pageSize|每页显示数量' => 'require',
            ]);
            $where = [];
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['type_id'])) {
                $where[] = ['type_id', '=', $param['type_id']];
            }
            if (!empty($param['status'])) {
                $where[] = ['status', '=', $param['status']];
            }
            if (isset($param['sign_review']) && strlen($param['sign_review'])) {
                $where[] = ['enroll_review', '=', $param['sign_review']];
            }
            if (isset($param['is_sign']) && strlen($param['is_sign'])) {
                $where[] = ['is_sign', '=', $param['is_sign']];
            }
            if (!empty($param['uid'])) {
                $where[] = ['uid', '=', $param['uid']];
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $GroupActivityTaskModel = new GroupActivityTaskModel();
            $query = $GroupActivityTaskModel->where($where);
            $data = $query->with([
                'typeName',
                'user' => function ($query) {
                    $query->with(['roleName']);
                }
            ])->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item){
                if (empty($item['role_name'])){
                    $item['role_name'] = '超级管理员';
                }
            }
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 活动编辑详情
     * @return bool|string
     */
    public function updateInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $GroupActivityTaskModel = new GroupActivityTaskModel();
            $info = $GroupActivityTaskModel->with([
                'taskDepartment',
                'taskRatingScale' => function ($query) {
                    $query->with(['RatingScale']);
                }
            ])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除活动
     * @return bool|string
     */
    public function del(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $GroupActivityTaskModel = new GroupActivityTaskModel();
            if (is_array($param['id'])) {
                $GroupActivityTaskModel->where('id', 'in', $param['id'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            } else {
                $GroupActivityTaskModel->where('id', '=', $param['id'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 活动编辑
     * @return bool|string
     */
    public function update(): bool|string
    {
        $GroupActivityTaskModel = new GroupActivityTaskModel();
        $GroupActivityTaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $info = $GroupActivityTaskModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if (!empty($param['enroll_start_time']) && !empty($param['enroll_end_time'])) {
                if ($param['enroll_start_time'] >= time() && $param['enroll_end_time'] <= time()) {
                    $param['status'] = 2;
                }
            }
            $GroupActivityTaskDepartmentModel = new GroupActivityTaskDepartmentModel();
            $GroupActivityTaskRatingScaleModel = new GroupActivityTaskRatingScaleModel();
            if (!empty($param['department_del'])){
                $GroupActivityTaskDepartmentModel->where('id', 'in', $param['department_del'])->delete();
            }
            if (!empty($param['rating_scale_del'])){
                $GroupActivityTaskRatingScaleModel->where('id', 'in', $param['rating_scale_del'])->delete();
            }
            //活动部门
            if (!empty($param['department'])) {
                $departmentData = [];
                foreach ($param['department'] as $v) {
                    $department = [
                        'department_id' => $v['department_id']
                    ];
                    if (!empty($v['id'])){
                        $department['id'] = $v['id'];
                    }else{
                        $department['task_id'] = $param['id'];
                        $department['time'] = time();
                    }
                    $departmentData[] = $department;
                }
                if (!empty($departmentData)){
                    $GroupActivityTaskDepartmentModel->saveAll($departmentData);
                }
                unset($param['department']);
            }
            //活动测评量表
            if (!empty($param['rating_scale'])) {
                foreach ($param['rating_scale'] as $v) {
                    $rating_scale = [
                        'rating_scale_id' => $v['rating_scale_id']
                    ];
                    if (!empty($v['id'])){
                        $rating_scale['id'] = $v['id'];
                    }else{
                        $rating_scale['task_id'] = $param['id'];
                        $rating_scale['time'] = time();
                    }
                    $ratingScaleData[] = $rating_scale;
                }
                if (!empty($ratingScaleData)){
                    $GroupActivityTaskRatingScaleModel->saveAll($ratingScaleData);
                }
                unset($param['rating_scale']);
            }
            $info->save($param);
            $GroupActivityTaskModel->commit();
            return success();
        } catch (\Exception $e) {
            $GroupActivityTaskModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 报名列表
     * @return bool|string
     */
    public function auditList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'pageSize|每页显示数量' => 'require',
                'audit_status|状态' => 'require'
            ]);
            $where[] = ['task_id', '=', $param['id']];
            $where[] = ['audit_status', '=', $param['audit_status']];
            $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
            $query = $GroupActivityTaskUserModel->where($where);
            $data = $query->with([
                'user',
                'result' => function ($query) {
                    $query->with(['RatingScale']);
                }
            ])->paginate($param['pageSize'])->toArray();
            $UserService = new UserService($this->app);
            $DepartmentData = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
            foreach ($data['data'] as &$value) {
                $value['department_name'] = $DepartmentData[$value['department_id']]['all_name'] ?? '--';
            }
            $data['ids'] = $query->column('id');
            $GroupActivityTaskModel = new GroupActivityTaskModel();
            $taskInfo = $GroupActivityTaskModel->withCount(['taskRatingScale'])->find($param['id']);
            $count = $GroupActivityTaskUserModel->where('task_id','=',$param['id'])->count();
            return success([
                'data' => $data,
                'max_participation' => $taskInfo['max_participation'],
                'task_rating_scale_count' => $taskInfo['task_rating_scale_count'],
                'count' => $count,
                'is_task' => $taskInfo['is_task'],
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 签到列表
     * @return bool|string
     */
    public function signList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'pageSize|每页显示数量' => 'require',
                'is_sign|状态' => 'require'
            ]);
            $where[] = ['task_id', '=', $param['id']];
            $where[] = ['is_sign', '=', $param['is_sign']];
            $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
            $query = $GroupActivityTaskUserModel->where($where);
            $data = $query->with([
                'user',
                'result' => function ($query) {
                    $query->with(['RatingScale']);
                }
            ])->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            $UserService = new UserService($this->app);
            $DepartmentData = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
            foreach ($data['data'] as &$value) {
                $value['department_name'] = $DepartmentData[$value['department_id']]['all_name'] ?? '--';
            }
            $GroupActivityTaskModel = new GroupActivityTaskModel();
            $taskInfo = $GroupActivityTaskModel->withCount(['taskRatingScale'])->find($param['id']);
            $count = $GroupActivityTaskUserModel->where([
                ['task_id','=',$param['id']],
                ['audit_status','=',2]
            ])->count();
            return success([
                'data' => $data,
                'max_participation' => $taskInfo['max_participation'],
                'task_rating_scale_count' => $taskInfo['task_rating_scale_count'],
                'count' => $count,
                'is_task' => $taskInfo['is_task']
            ]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 审核
     * @return bool|string
     */
    public function audit(): bool|string
    {
        $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
        $GroupActivityTaskUserModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'audit_status|状态' => 'require|in:2,3'
            ]);
            $GroupActivityTaskUserModel->where('id', 'in', $param['id'])->update([
                'audit_status' => $param['audit_status'],
                'status' => $param['audit_status'],
                'audit_time' => time()
            ]);
            $task_id = $GroupActivityTaskUserModel->where('id', 'in', $param['id'])->value('task_id');
            if ($param['audit_status'] == 2) {
                $GroupActivityTaskModel = new GroupActivityTaskModel();
                $taskInfo = $GroupActivityTaskModel->find($task_id);
                //自增报名人数
                $taskInfo->inc('enroll_num', count($param['id']))->save();
            }
            $GroupActivityTaskUserModel->commit();
            return success();
        } catch (\Exception $e) {
            $GroupActivityTaskUserModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 用户量表测评结果
     * @return bool|string
     */
    public function userResult(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $ReportService = new ReportService($this->app);
            return success($ReportService->getGroupActivityReportInfo($param['id']));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function userResult2(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $ReportService = new ReportService($this->app);
            return success($ReportService->getGroupActivityEvaluationReportInfo($param['id']));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $GroupActivityTaskModel = new GroupActivityTaskModel();
            $info = $GroupActivityTaskModel->with([
                'user' => function ($query) {
                    $query->with(['roleName']);
                },
                'typeName',
                'taskRatingScale' => function ($query) {
                    $query->with(['RatingScale']);
                },
                'taskDepartment',
                'taskImg'
            ])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            if (!empty($info['taskDepartment'])) {
                $UserService = new UserService($this->app);
                $DepartmentData = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($info['taskDepartment'] as &$value) {
                    $value['department_name'] = $DepartmentData[$value['department_id']]['all_name'] ?? '--';
                }
            }
            $info['role_name'] = $info['role_name'] ?? '超级管理员';
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 活动数据统计
     * @return bool|string
     */
    public function statistics(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $GroupActivityTaskModel = new GroupActivityTaskModel();
            $taskInfo = $GroupActivityTaskModel->withCount(['taskRatingScale'])->find($param['id']);
            if (!$taskInfo) throw new \Exception('参数错误！');
            $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
            //报名人数
            $uid = $GroupActivityTaskUserModel->where('task_id', '=', $param['id'])->column('uid');
            $data['sign_up'] = count(array_unique($uid));
            //审核通过人数
            $uid = $GroupActivityTaskUserModel->where([
                ['task_id', '=', $param['id']],
                ['audit_status', '=', 2]
            ])->column('uid');
            $data['pass_num'] = count(array_unique($uid));
            //实际参与男生人数
            $UserModel = new UserModel();
            $data['boy'] = $UserModel->where([
                ['id', 'in', $uid],
                ['sex', '=', 1]
            ])->count();
            //实际参与女生人数
            $data['girl'] = $data['pass_num'] - $data['boy'];
            //请假取消人数
            $uid = $GroupActivityTaskUserModel->where([
                ['task_id', '=', $param['id']],
                ['status', '=', 5]
            ])->column('uid');
            $data['cancel_num'] = count(array_unique($uid));
            //实际签到人数
            $uid = $GroupActivityTaskUserModel->where([
                ['task_id', '=', $param['id']],
                ['is_sign', '=', 1]
            ])->column('uid');
            $data['sign_num'] = count(array_unique($uid));
            //完成前置测评任务数
            $GroupActivityTaskUserResultModel = new GroupActivityTaskUserResultModel();
            $ResultList = $GroupActivityTaskUserResultModel->field('id,task_user_id')->where('task_id', '=', $param['id'])->select()->toArray();
            $ResultData = [];
            foreach ($ResultList as $value) {
                if (isset($ResultData[$value['task_user_id']])) {
                    $ResultData[$value['task_user_id']]++;
                } else {
                    $ResultData[$value['task_user_id']] = 1;
                }
            }
            $task_user_id = [];
            $task_user_id2 = [];
            foreach ($ResultData as $value) {
                if ($value == $taskInfo['task_rating_scale_count']) {
                    $task_user_id[] = $value;
                } else {
                    $task_user_id2[] = $value;
                }
            }
            $uid = $GroupActivityTaskUserModel->where([
                ['id', 'in', $task_user_id],
                ['audit_status', '=', 2]
            ])->column('uid');
            $data['finish_num'] = count(array_unique($uid));
            //部分完成前置测评数
            $uid = $GroupActivityTaskUserModel->where([
                ['id', 'in', $task_user_id2],
                ['audit_status', '=', 2]
            ])->column('uid');
            $data['part_finish_num'] = count(array_unique($uid));
            //未完成前置测评数
            $data['incomplete_num'] = $data['pass_num'] - $data['finish_num'] - $data['part_finish_num'];

            //参与测评人数
            $uid = $GroupActivityTaskUserResultModel->where('task_id', '=', $param['id'])->column('uid');
            $data['evaluation_num'] = count(array_unique($uid));
            //正常人数
            $uid = $GroupActivityTaskUserResultModel->where([
                ['task_id', '=', $param['id']],
                ['is_warning', '=', 0]
            ])->column('uid');
            $data['normal_num'] = count(array_unique($uid));
            $uid = $GroupActivityTaskUserResultModel->where([
                ['task_id', '=', $param['id']],
                ['is_warning', '=', 1]
            ])->column('uid');
            //预警人数
            $data['warning_num'] = count(array_unique($uid));
            //预警男生
            $data['boy_warning_num'] = $UserModel->where([
                ['id', 'in', $uid],
                ['sex', '=', 1]
            ])->count();
            //预警女生
            $data['girl_warning_num'] = $data['warning_num'] - $data['boy_warning_num'];
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 用户评论反馈
     * @return bool|string
     */
    public function commentList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'pageSize|每页显示数量' => 'require',
            ]);
            $GroupActivityTaskCommentModel = new GroupActivityTaskCommentModel();
            $data = $GroupActivityTaskCommentModel->where('task_id', '=', $param['id'])->with(['user'])->paginate($param['pageSize'])->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 发布人选择器
     * @return bool|string
     */
    public function PublisherSelector(): bool|string
    {
        try {
            $GroupActivityTaskModel = new GroupActivityTaskModel();
            $uid = $GroupActivityTaskModel->where('unit_id', '=', $this->userData['unit_id'])->column('uid');
            $UserModel = new UserModel();
            $data = $UserModel->where('id', 'in', $uid)->field('id,name')->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 结束活动
     * @return bool|string
     */
    public function end(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $GroupActivityTaskModel = new GroupActivityTaskModel();
            $info = $GroupActivityTaskModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info->save([
                'status' => 5,
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 总结
     * @return bool|string
     */
    public function summarize(): bool|string
    {
        $GroupActivityTaskModel = new GroupActivityTaskModel();
        $GroupActivityTaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $info = $GroupActivityTaskModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if (!empty($param['process_summary']) || !empty($param['effect'])) {
                $info->save($param);
            }
            $GroupActivityTaskImgModel = new GroupActivityTaskImgModel();
            $GroupActivityTaskImgModel->where('task_id', '=', $param['id'])->delete();
            if (!empty($param['img'])) {
                $imgData = [];
                foreach ($param['img'] as $img) {
                    $imgData[] = [
                        'task_id' => $param['id'],
                        'img' => $img,
                        'time' => time()
                    ];
                }
                $GroupActivityTaskImgModel->insertAll($imgData);
            }
            $GroupActivityTaskModel->commit();
            return success();
        } catch (\Exception $e) {
            $GroupActivityTaskModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 请假详情
     * @return bool|string
     */
    public function leaveInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
            $info = $GroupActivityTaskUserModel->with(['user'])->find($param['id']);
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 审核请假
     * @return bool|string
     */
    public function auditLeave(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'leave_status|状态' => 'require|in:2,3'
            ]);
            $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
            $info = $GroupActivityTaskUserModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $GroupActivityTaskModel = new GroupActivityTaskModel();
            $uid = $GroupActivityTaskModel->where('id', '=', $info['task_id'])->column('uid');
            if ($uid != $this->userData['id']) throw new \Exception('活动发布者才能审核！');
            $update['leave_status'] = $param['leave_status'];
            if ($param['leave_status'] == 2) {
                $update['status'] = 5;
            }
            $info->save($update);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function auditExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'task_id|活动ID' => 'require'
            ]);
            $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
            $GroupActivityTaskRatingScaleModel = new GroupActivityTaskRatingScaleModel();
            $rating_scale_count = $GroupActivityTaskRatingScaleModel->where('task_id', '=', $param['task_id'])->count();
            $data = $GroupActivityTaskUserModel->where('id','in',$param['id'])->with(['user'])->withCount(['result'])->select()->toArray();

            // 创建新的Spreadsheet对象
            $spreadsheet = new Spreadsheet();
            // 获取活动的工作表
            $sheet = $spreadsheet->getActiveSheet();
            // 设置工作表标题
            $sheet->setTitle('待审核');
            // 设置单元格数据
            $sheet->setCellValue('A1', '名称');
            $sheet->setCellValue('B1', '联系方式');
            $sheet->setCellValue('C1', '性别');
            $sheet->setCellValue('D1', '年龄');
            $sheet->setCellValue('E1', '身份证号');
            $sheet->setCellValue('F1', '注册账号');
            $sheet->setCellValue('G1', '所在部门');
            $sheet->setCellValue('H1', '学籍状态');
            $sheet->setCellValue('I1', '审核情况');
            $sheet->setCellValue('J1', '前置任务完成情况');
            $sheet->setCellValue('K1', '报名时间');
            if (count($data) > 0) {
                $key = 2;
                $UserService = new UserService($this->app);
                $DelDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($data as $item) {
                    //学籍状态
                    $student_name = match ($item['student_status']) {
                        0 => '不限',
                        1 => '在读',
                        2 => '已毕业',
                        3 => '已退学',
                        4 => '休学',
                        default => '--',
                    };
                    if ($rating_scale_count > 0){
                        if ($item['result_count'] >= $rating_scale_count){
                            $is_finish = '已完成';
                        }else{
                            $is_finish = '未完成';
                        }
                    }else{
                        $is_finish = '--';
                    }
                    // 设置单元格数据
                    $sheet->setCellValue('A'.$key, $item['user_name']??'--');
                    $sheet->setCellValue('B'.$key, $item['phone']??'--');
                    $sheet->getStyle('B'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('C'.$key, $item['sex'] == 1 ? '男' : '女');
                    $sheet->setCellValue('D'.$key, $item['age']?:'--');
                    $sheet->setCellValue('E'.$key, $item['id_card']?:'--');
                    $sheet->getStyle('E'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('F'.$key, $item['username']?:'--');
                    $sheet->setCellValue('G'.$key, $DelDepartment[$item['department_id']]['all_name']??'--');
                    $sheet->setCellValue('H'.$key, $student_name);
                    $sheet->setCellValue('I'.$key, '待审核');
                    $sheet->setCellValue('J'.$key, $is_finish);
                    $sheet->setCellValue('K'.$key, date('Y-m-d H:i:s', $item['time']));
                    $key++;
                }
            }
            $writer = new Xlsx($spreadsheet);
            $ext = '.xlsx';
            $save_name = '/export/group_activity'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            $writer->save('./public' . $save_name . $ext);
            return success(oss('./public' . $save_name . $ext, $ext));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function auditExport2(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'task_id|活动ID' => 'require'
            ]);
            $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
            $GroupActivityTaskRatingScaleModel = new GroupActivityTaskRatingScaleModel();
            $rating_scale_count = $GroupActivityTaskRatingScaleModel->where('task_id', '=', $param['task_id'])->count();
            $data = $GroupActivityTaskUserModel->where('id','in',$param['id'])->with(['user'])->withCount(['result'])->select()->toArray();

            // 创建新的Spreadsheet对象
            $spreadsheet = new Spreadsheet();
            // 获取活动的工作表
            $sheet = $spreadsheet->getActiveSheet();
            // 设置工作表标题
            $sheet->setTitle('已允许');
            // 设置单元格数据
            $sheet->setCellValue('A1', '名称');
            $sheet->setCellValue('B1', '联系方式');
            $sheet->setCellValue('C1', '性别');
            $sheet->setCellValue('D1', '年龄');
            $sheet->setCellValue('E1', '身份证号');
            $sheet->setCellValue('F1', '注册账号');
            $sheet->setCellValue('G1', '所在部门');
            $sheet->setCellValue('H1', '学籍状态');
            $sheet->setCellValue('I1', '可否正常参与活动');
            $sheet->setCellValue('J1', '审核情况');
            $sheet->setCellValue('K1', '前置任务完成情况');
            $sheet->setCellValue('L1', '报名时间');
            if (count($data) > 0) {
                $key = 2;
                $UserService = new UserService($this->app);
                $DelDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($data as $item) {
                    //学籍状态
                    $student_name = match ($item['student_status']) {
                        0 => '不限',
                        1 => '在读',
                        2 => '已毕业',
                        3 => '已退学',
                        4 => '休学',
                        default => '--',
                    };
                    if ($rating_scale_count > 0){
                        if ($item['result_count'] >= $rating_scale_count){
                            $is_finish = '已完成';
                        }else{
                            $is_finish = '未完成';
                        }
                    }else{
                        $is_finish = '--';
                    }
                    // 设置单元格数据
                    $sheet->setCellValue('A'.$key, $item['user_name']??'--');
                    $sheet->setCellValue('B'.$key, $item['phone']??'--');
                    $sheet->getStyle('B'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('C'.$key, $item['sex'] == 1 ? '男' : '女');
                    $sheet->setCellValue('D'.$key, $item['age']?:'--');
                    $sheet->setCellValue('E'.$key, $item['id_card']?:'--');
                    $sheet->getStyle('E'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('F'.$key, $item['username']?:'--');
                    $sheet->setCellValue('G'.$key, $DelDepartment[$item['department_id']]['all_name']??'--');
                    $sheet->setCellValue('H'.$key, $student_name);
                    $sheet->setCellValue('I'.$key, $item['leave_status']?'有请假':'正常赴约');
                    $sheet->setCellValue('J'.$key, '已允许');
                    $sheet->setCellValue('K'.$key, $is_finish);
                    $sheet->setCellValue('L'.$key, date('Y-m-d H:i:s', $item['time']));
                    $key++;
                }
            }
            $writer = new Xlsx($spreadsheet);
            $ext = '.xlsx';
            $save_name = '/export/group_activity'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            $writer->save('./public' . $save_name . $ext);
            return success(oss('./public' . $save_name . $ext, $ext));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function auditExport3(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'task_id|活动ID' => 'require'
            ]);
            $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
            $GroupActivityTaskRatingScaleModel = new GroupActivityTaskRatingScaleModel();
            $rating_scale_count = $GroupActivityTaskRatingScaleModel->where('task_id', '=', $param['task_id'])->count();
            $data = $GroupActivityTaskUserModel->where('id','in',$param['id'])->with(['user'])->withCount(['result'])->select()->toArray();

            // 创建新的Spreadsheet对象
            $spreadsheet = new Spreadsheet();
            // 获取活动的工作表
            $sheet = $spreadsheet->getActiveSheet();
            // 设置工作表标题
            $sheet->setTitle('待审核');
            // 设置单元格数据
            $sheet->setCellValue('A1', '名称');
            $sheet->setCellValue('B1', '联系方式');
            $sheet->setCellValue('C1', '性别');
            $sheet->setCellValue('D1', '年龄');
            $sheet->setCellValue('E1', '身份证号');
            $sheet->setCellValue('F1', '注册账号');
            $sheet->setCellValue('G1', '所在部门');
            $sheet->setCellValue('H1', '学籍状态');
            $sheet->setCellValue('I1', '审核情况');
            $sheet->setCellValue('J1', '前置任务完成情况');
            $sheet->setCellValue('K1', '报名时间');
            if (count($data) > 0) {
                $key = 2;
                $UserService = new UserService($this->app);
                $DelDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($data as $item) {
                    //学籍状态
                    $student_name = match ($item['student_status']) {
                        0 => '不限',
                        1 => '在读',
                        2 => '已毕业',
                        3 => '已退学',
                        4 => '休学',
                        default => '--',
                    };
                    if ($rating_scale_count > 0){
                        if ($item['result_count'] >= $rating_scale_count){
                            $is_finish = '已完成';
                        }else{
                            $is_finish = '未完成';
                        }
                    }else{
                        $is_finish = '--';
                    }
                    // 设置单元格数据
                    $sheet->setCellValue('A'.$key, $item['user_name']??'--');
                    $sheet->setCellValue('B'.$key, $item['phone']??'--');
                    $sheet->getStyle('B'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('C'.$key, $item['sex'] == 1 ? '男' : '女');
                    $sheet->setCellValue('D'.$key, $item['age']?:'--');
                    $sheet->setCellValue('E'.$key, $item['id_card']?:'--');
                    $sheet->getStyle('E'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('F'.$key, $item['username']?:'--');
                    $sheet->setCellValue('G'.$key, $DelDepartment[$item['department_id']]['all_name']??'--');
                    $sheet->setCellValue('H'.$key, $student_name);
                    $sheet->setCellValue('I'.$key, '已拒绝');
                    $sheet->setCellValue('J'.$key, $is_finish);
                    $sheet->setCellValue('K'.$key, date('Y-m-d H:i:s', $item['time']));
                    $key++;
                }
            }
            $writer = new Xlsx($spreadsheet);
            $ext = '.xlsx';
            $save_name = '/export/group_activity'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            $writer->save('./public' . $save_name . $ext);
            return success(oss('./public' . $save_name . $ext, $ext));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function signExport(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'task_id|活动ID' => 'require'
            ]);
            $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
            $GroupActivityTaskRatingScaleModel = new GroupActivityTaskRatingScaleModel();
            $rating_scale_count = $GroupActivityTaskRatingScaleModel->where('task_id', '=', $param['task_id'])->count();
            $data = $GroupActivityTaskUserModel->where('id','in',$param['id'])->with(['user'])->withCount(['result'])->select()->toArray();

            // 创建新的Spreadsheet对象
            $spreadsheet = new Spreadsheet();
            // 获取活动的工作表
            $sheet = $spreadsheet->getActiveSheet();
            // 设置工作表标题
            $sheet->setTitle('正常签到名单');
            // 设置单元格数据
            $sheet->setCellValue('A1', '名称');
            $sheet->setCellValue('B1', '联系方式');
            $sheet->setCellValue('C1', '性别');
            $sheet->setCellValue('D1', '年龄');
            $sheet->setCellValue('E1', '身份证号');
            $sheet->setCellValue('F1', '注册账号');
            $sheet->setCellValue('G1', '所在部门');
            $sheet->setCellValue('H1', '学籍状态');
            $sheet->setCellValue('I1', '前置任务完成情况');
            $sheet->setCellValue('J1', '是否签到');
            $sheet->setCellValue('K1', '签到时间');
            if (count($data) > 0) {
                $key = 2;
                $UserService = new UserService($this->app);
                $DelDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($data as $item) {
                    //学籍状态
                    $student_name = match ($item['student_status']) {
                        0 => '不限',
                        1 => '在读',
                        2 => '已毕业',
                        3 => '已退学',
                        4 => '休学',
                        default => '--',
                    };
                    if ($rating_scale_count > 0){
                        if ($item['result_count'] >= $rating_scale_count){
                            $is_finish = '已完成';
                        }else{
                            $is_finish = '未完成';
                        }
                    }else{
                        $is_finish = '--';
                    }
                    // 设置单元格数据
                    $sheet->setCellValue('A'.$key, $item['user_name']??'--');
                    $sheet->setCellValue('B'.$key, $item['phone']??'--');
                    $sheet->getStyle('B'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('C'.$key, $item['sex'] == 1 ? '男' : '女');
                    $sheet->setCellValue('D'.$key, $item['age']?:'--');
                    $sheet->setCellValue('E'.$key, $item['id_card']?:'--');
                    $sheet->getStyle('E'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('F'.$key, $item['username']?:'--');
                    $sheet->setCellValue('G'.$key, $DelDepartment[$item['department_id']]['all_name']??'--');
                    $sheet->setCellValue('H'.$key, $student_name);
                    $sheet->setCellValue('I'.$key, $is_finish);
                    $sheet->setCellValue('J'.$key, '已签到');
                    $sheet->setCellValue('K'.$key, $item['sign_time']?date('Y-m-d H:i:s', $item['sign_time']):'--');
                    $key++;
                }
            }
            $writer = new Xlsx($spreadsheet);
            $ext = '.xlsx';
            $save_name = '/export/group_activity'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            $writer->save('./public' . $save_name . $ext);
            return success(oss('./public' . $save_name . $ext, $ext));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    public function signExport2(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
                'task_id|活动ID' => 'require'
            ]);
            $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
            $GroupActivityTaskRatingScaleModel = new GroupActivityTaskRatingScaleModel();
            $rating_scale_count = $GroupActivityTaskRatingScaleModel->where('task_id', '=', $param['task_id'])->count();
            $data = $GroupActivityTaskUserModel->where('id','in',$param['id'])->with(['user'])->withCount(['result'])->select()->toArray();

            // 创建新的Spreadsheet对象
            $spreadsheet = new Spreadsheet();
            // 获取活动的工作表
            $sheet = $spreadsheet->getActiveSheet();
            // 设置工作表标题
            $sheet->setTitle('未签到名单');
            // 设置单元格数据
            $sheet->setCellValue('A1', '名称');
            $sheet->setCellValue('B1', '联系方式');
            $sheet->setCellValue('C1', '性别');
            $sheet->setCellValue('D1', '年龄');
            $sheet->setCellValue('E1', '身份证号');
            $sheet->setCellValue('F1', '注册账号');
            $sheet->setCellValue('G1', '所在部门');
            $sheet->setCellValue('H1', '学籍状态');
            $sheet->setCellValue('I1', '前置任务完成情况');
            $sheet->setCellValue('J1', '是否签到');
            $sheet->setCellValue('K1', '未签到原因');
            if (count($data) > 0) {
                $key = 2;
                $UserService = new UserService($this->app);
                $DelDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($data as $item) {
                    //学籍状态
                    $student_name = match ($item['student_status']) {
                        0 => '不限',
                        1 => '在读',
                        2 => '已毕业',
                        3 => '已退学',
                        4 => '休学',
                        default => '--',
                    };
                    if ($rating_scale_count > 0){
                        if ($item['result_count'] >= $rating_scale_count){
                            $is_finish = '已完成';
                        }else{
                            $is_finish = '未完成';
                        }
                    }else{
                        $is_finish = '--';
                    }
                    $reason = match ($item['status']) {
                        4 => '爽约',
                        5 => '请假',
                        default => '--',
                    };
                    // 设置单元格数据
                    $sheet->setCellValue('A'.$key, $item['user_name']??'--');
                    $sheet->setCellValue('B'.$key, $item['phone']??'--');
                    $sheet->getStyle('B'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('C'.$key, $item['sex'] == 1 ? '男' : '女');
                    $sheet->setCellValue('D'.$key, $item['age']?:'--');
                    $sheet->setCellValue('E'.$key, $item['id_card']?:'--');
                    $sheet->getStyle('E'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                    $sheet->setCellValue('F'.$key, $item['username']?:'--');
                    $sheet->setCellValue('G'.$key, $DelDepartment[$item['department_id']]['all_name']??'--');
                    $sheet->setCellValue('H'.$key, $student_name);
                    $sheet->setCellValue('I'.$key, $is_finish);
                    $sheet->setCellValue('J'.$key, '未签到');
                    $sheet->setCellValue('K'.$key, $reason);
                    $key++;
                }
            }
            $writer = new Xlsx($spreadsheet);
            $ext = '.xlsx';
            $save_name = '/export/group_activity'.date('Ym').'/'.date('d').'_'.time().uniqid();
            $file_path  = dirname('./public' . $save_name.$ext);
            folder_build($file_path);
            $writer->save('./public' . $save_name . $ext);
            return success(oss('./public' . $save_name . $ext, $ext));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }
}